fs = require 'fs'
nib = require 'nib'
gulp = require 'gulp'
path = require 'path'
_ = require 'underscore'
crc32 = require 'buffer-crc32'
cleanCss = require 'gulp-clean-css'
$ = require('gulp-load-plugins')()

srcPath = 'src'
destPath = 'dest'
staticsSrcPath = path.join srcPath, 'public'
staticsDestPath = path.join destPath, 'public'

coffee_src = 'src/**/*.coffee'
stylus_src ='src/**/*.styl'
copy_src = 'src/**/*'

# 编译coffee文件
gulp.task 'js',()->
  gulp.src coffee_src
    .pipe $.coffee()
    .pipe gulp.dest destPath

# 压缩js文件
gulp.task 'uglify', ['js'], ()->
  gulp.src [staticsSrcPath+'/**/*.js', staticsDestPath+'/**/*.js']
    .pipe $.jshint()
    .pipe $.uglify {mangle:{except : ['$', 'require', 'exports', 'module']}}
    .pipe gulp.dest staticsDestPath

# 编译styl文件
gulp.task 'css',() ->
  gulp.src stylus_src
    .pipe $.stylus
      error: true
      use: [nib()]
    .pipe gulp.dest destPath

# 删除样式文件
gulp.task 'cleancss', ['css', 'copy'],() ->
  gulp.src staticsDestPath+'/**/*.css'
    .pipe cleanCss
      compatibility :'ie7'
    .pipe gulp.dest staticsDestPath

# 图片url进行base64编码
gulp.task 'base64',['merge_static'], () ->
  gulp.src staticsDestPath+'/**/*.css'
    .pipe $.base64({
      extensions: ['png','jpg','gif','ico'],
      maxImageSize: 5000 * 1024, 
      debug: false
    })
    .pipe gulp.dest staticsDestPath

# 复制静态文件
gulp.task 'copy', () ->
  gulp.src [copy_src,'!src/**/*.coffee', '!src/**/*.styl', '!src/public/**/*.js']
    .pipe gulp.dest destPath

# 合并静态文件
gulp.task 'merge_static', ['cleancss','uglify'],() ->
  Merge = require './src/helpers/merge'
  fs.mkdir path.join staticsDestPath, 'merge'
  comps = require path.join __dirname, 'src/comps.json'
  mergeInfo = require path.join __dirname, 'src/merge.json'
  merge = new Merge mergeInfo
  result = merge.getMergeList comps, staticsDestPath
  _.each result, (files, saveFile) ->
    merge.merge __dirname, saveFile, files

# 生成静态文件的crc32
gulp.task 'crc32',['base64'] ,()->
  crc32Infos = {}
  gulp.src [staticsDestPath+'/**/*.js',staticsDestPath+'/**/*.css']
    .pipe($.tap (file)->
      buf = file.contents.toString() 
      destFile = '/'+path.relative(staticsDestPath,file.path).replace(/\\/gi,'/')
      crc32Infos[destFile] = crc32.unsigned buf
      fs.writeFileSync path.join(destPath, 'crc32.json'), JSON.stringify( crc32Infos, null, 2)
    )

# 删除dest目录
gulp.task 'clean', (cb) ->
  gulp.src destPath
    .pipe $.clean()

gulp.task 'default', ['clean'], () ->
  gulp.start 'js', 'uglify', 'copy','css','cleancss','base64', 'merge_static','crc32'